package com.vvv.threadpool;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author vvv
 * @date 2023-10-22 15 40
 * discription 使用
 */
public class CustomThreadPoolV1 {
    public static void main(String[] args) {
        ThreadPool threadPool = new ThreadPool(1, 1000
                , TimeUnit.MILLISECONDS, 1
                , ((queue, task) -> {

            // 死等策略
//            queue.put(task);
            // 超时等待
            queue.offer(task, 1000, TimeUnit.MILLISECONDS);
            // 放弃
//            System.out.println("放弃");
            // 抛异常
//            throw new RuntimeException("main");
            // 自己执行
//            task.run();
        }));


        for (int i = 0; i < 3; i++) {
            int j = i;
            threadPool.execute(() -> {
                Thread thread = Thread.currentThread();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(thread.getName() + "线程执行了这个任务" + j);
            });
        }

    }
}

@FunctionalInterface
interface RejectPolicy<T> {
    void reject(BlockingQueueV1<T> queue, T task);
}

class ThreadPool {
    // 1. 阻塞队列
    private BlockingQueueV1<Runnable> taskQueue;
    // 2. 线程集合
    private HashSet<Worker> workers = new HashSet<>();
    // 3. 核心线程数
    private int coreSize;
    // 4. 任务超时时间
    private long timeout;
    // 4.1 时间单位
    private TimeUnit timeUnit;
    // 5 拒绝策略
    private RejectPolicy<Runnable> rejectPolicy;

    public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapacity, RejectPolicy<Runnable> rejectPolicy) {
        this.coreSize = coreSize;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
        this.taskQueue = new BlockingQueueV1<>(queueCapacity);
        this.rejectPolicy = rejectPolicy;
    }

    public void execute(Runnable task) {
        // 如果当前任务数<coreSize，那么直接交给worker去执行
        // 如果当前任务数>coreSize，则把任务放到taskqueue里面

        // workers 属于共享资源，同时又有读写操作，所以要加锁
        synchronized (workers) {
            if (workers.size() < coreSize) {
                Worker worker = new Worker(task);
                workers.add(worker);
                worker.start();
            } else {
                // 队列满时，会让main线程死等
                //taskQueue.put(task);
                taskQueue.tryPut(rejectPolicy, task);
            }
        }
    }

    class Worker extends Thread{
        private volatile Runnable task;

        public Worker(Runnable task) {
            this.task = task;
        }

        @Override
        public void run() {
            // 1. 如果有task，那么就执行task
            // 2. 如果没有task，则去任务队列里面去拉去task
            while (task != null || (task = taskQueue.poll(timeout, timeUnit)) != null) {
                try {
                    task.run();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    task = null;
                }
            }
            // 共享资源
            synchronized (workers) {
                workers.remove(this);
            }
        }
    }
}

class BlockingQueueV1<T> {
    // 1. 阻塞队列
    private Deque<T> queue = new ArrayDeque<>();
    // 2. 消费者（ThreadPool）争抢的锁
    private ReentrantLock lock = new ReentrantLock();
    // 3. 队列为空的休息室，给消费者（ThreadPool）用的
    private Condition fullWaitSet = lock.newCondition();
    // 4. 队列为满的休息室，给生产者用的main
    private Condition emptyWaitSet = lock.newCondition();
    // 5. 阻塞队列大小
    private int capacity;

    public BlockingQueueV1(int capacity) {
        this.capacity = capacity;
    }

    // 带超时的消费
    public T poll(long timeout, TimeUnit timeUnit) {
        lock.lock();
        try {
            long nanos = timeUnit.toNanos(timeout);
            while (queue.isEmpty()) {
                try {
                    if (nanos <= 0) {
                        return null;
                    }
                    nanos = emptyWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            T t = queue.removeFirst();
            // 可以思考一下这里signal和signalAll的区别
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }

    // 5. 消费
    public T take() {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                try {
                    emptyWaitSet.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            T t = queue.removeFirst();
            // 可以思考一下这里signal和signalAll的区别
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }
    // 6. 生产
    public void put(T t) {
        lock.lock();
        try {
            while (capacity == queue.size()) {
                try {
                    fullWaitSet.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            queue.addLast(t);
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
    }
    // 6. 生产
    public boolean offer(T t, long timeout, TimeUnit timeUnit) {
        lock.lock();
        try {
            long nanos = timeUnit.toNanos(timeout);
            while (capacity == queue.size()) {
                try {
                    if (nanos <= 0) {
                        return false;
                    }
                    nanos = fullWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            queue.addLast(t);
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
        return true;
    }
    // 7. 获取大小
    public int size() {
        lock.lock();
        try {
            return this.capacity;
        } finally {
            lock.unlock();
        }
    }

    public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
        lock.lock();
        try {
            if (queue.size() < capacity) {
                queue.addLast(task);
                emptyWaitSet.signal();
            } else {
                rejectPolicy.reject(this, task);
            }
        } finally {
            lock.unlock();
        }
    }
}
